﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Weight.Dal;
using Weight.Model;

namespace Weight.Bll
{
    public  class BllRight
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ExeResult Add(RightEntity entity)
        {
            var result = ExeResult.Defalut();
            DalRight dal = new DalRight();
            RightEntity item = dal.GetByRoleId(entity.RoleId);
            bool b = false;
            if(item != null)
            {
                b = dal.Update(entity);
            }
            else
            {
                b = dal.Add(entity);
            }
            if(b)
            {
                return result = ExeResult.Success("设置成功!");
            }
            else
            {
                return result = ExeResult.Faild("设置失败!");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ExeResult Delete(string roleId)
        {
            var result = ExeResult.Defalut();
            DalRight dal = new DalRight();
            RightEntity item = dal.GetByRoleId(roleId);
            bool b = false;
            if (item != null)
            {
                b = dal.Delete(item.Id);
            }
            else
            {
                b = true;
            }
            if (b)
            {
                return result = ExeResult.Success("删除成功!");
            }
            else
            {
                return result = ExeResult.Faild("删除失败!");
            }
        }

        /// <summary>
        /// 根据角色Id 获取
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
       public RightEntity  GetByRoleId(string roleId)
        {
            return new DalRight().GetByRoleId(roleId);
        }

        /// <summary>
        /// 获取所有的权限
        /// </summary>
        /// <param name="roles">角色</param>
        /// <returns></returns>
        public List<string> GetRightByRoleName(List<string> roles)
        {
            List<string> rightList = new List<string>();
            if(roles != null && roles.Count > 0)
            {
                var rights = new DalRight().GetRightByRoleName(roles);
                StringBuilder rightBuider = new StringBuilder();
                foreach (var item in rights)
                {
                    rightBuider.Append(item.Rights).Append(",");
                }
                string rightStr = rightBuider.ToString();
                rightList.AddRange(rightStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                rightList = rightList.Distinct().ToList();
            }
            return rightList;
        }
    }
}
